<!--
 * @Author: 赵宇
 * @Description: 
 * @Date: 2023-03-14 15:17:35
 * @LastEditTime: 2023-04-24 10:44:16
 * @LastEditors: zhao 13370229059@163.com
 * @FilePath: \pcj\src\components\z-select\index.vue
-->
<template>
  <el-select v-model="select.value" :clearable="clearable" :multiple="multiple" :placeholder="placeholder" @visible-change="onVisibleChange" @change="onChange">
    <el-option v-for="item in select.options" :key="item.value" :label="item.label" :value="item.value" />
  </el-select>
</template>

<script setup>
import { post, get } from '@/api/index';
let props = defineProps({
  placeholder: {
    // 占位符
    type: String,
    default: '请输入'
  },
  modelValue: {
    // 传值
    type: [Array, Number],
    default: undefined
  },
  clearable: {
    type: Boolean,
    default: false
  },
  api: {
    // 远程请求接口地址
    type: String,
    default: 'User/GetSelectPage'
  },
  apiParams: {
    // 远程请求额外参数
    type: Object,
    default: () => {
      return {};
    }
  },
  options: {
    // 用于默认选择项
    type: Array,
    default: () => {
      return [];
    }
  },
  isReturnObj: {
    // 是否返回对象
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: false
  }
});
let select = reactive({
  value: undefined,
  options: [],
  params: {
    pageIndex: 1,
    pageSize: 20,
    keyword: ''
  }
});
watch(
  () => props.modelValue,
  val => {
    select.value = val;
  },
  {
    immediate: true
  }
);
watch(
  () => props.options,
  val => {
    select.options = val;
  },
  {
    immediate: true
  }
);
let emit = defineEmits(['update:modelValue', 'change']);

const onChange = val => {
  console.log(val);
  emit('update:modelValue', val);
  let value = null;
  if (props.isReturnObj) {
    value = !val ? { label: '0', value: null } : select.options.find(r => r.value === val);
  } else {
    value = val;
  }
  emit('change', value);
};
const onVisibleChange = async val => {
  if (!val) return;
  let params = { ...select.params, ...props.apiParams };
  let { result } = await post(props.api, params);
  let items = result.items || result;
  select.options = items.map(r => {
    return {
      label: r.name,
      value: r.id
    };
  });
};
</script>

<style lang="scss" scoped></style>
